package com.lwc.backendsinglestructure.strategy.sendStrategy;

import cn.hutool.core.util.StrUtil;
import com.lwc.backendsinglestructure.domain.dto.user.CaptchasForm;
import com.lwc.backendsinglestructure.exception.BusinessException;
import com.lwc.backendsinglestructure.exception.ErrorCode;
import com.lwc.backendsinglestructure.strategy.SendHandler;
import com.lwc.backendsinglestructure.utils.CaptchaUtil;
import com.lwc.backendsinglestructure.utils.cache.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 手机发送验证码
 */
@Component("PHONE_SEND")
@Slf4j
public class PhoneSendStrategy implements SendHandler {

    @Autowired
    private CacheUtil cacheUtil;

    @Override
    public Boolean sendCaptcha(CaptchasForm captchasForm) {
        // 1.先校验是否重复发送
        String existCaptcha = cacheUtil.get("captcha:" + captchasForm.getBusiness() + ":"+ captchasForm.getPhone());
        if(StrUtil.isNotBlank(existCaptcha)){
            throw new BusinessException(ErrorCode.REPEAT_CAPTCHA_ERROR);
        }
        // 1.校验手机是否为空 TODO 格式错误校验
        if(StrUtil.isBlank(captchasForm.getPhone())){
            throw new BusinessException(ErrorCode.PHONE_ERROR);
        }

        // 2.拼接出验证码
        String captcha = CaptchaUtil.generatePhoneCaptcha();
        log.info("验证码：" + captcha);

        try {
            // 3.调用api发送验证码(不同模板？)

            // 4。写入redis中记录 / 一分钟有效
            cacheUtil.set("captcha:" + captchasForm.getBusiness() + ":" + captchasForm.getPhone(), captcha, 300);
            return true;
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SEND_CAPTCHA_ERROR);
        }

    }
}
